<?php
namespace Admin\Controller;

use Admin\Controller\GlobalController;

class WeixinController extends GlobalController
{
    //杂志列表
    public function uploadarticles()
    {
        if (IS_POST) {
            include APP_PATH . './Common/Util/wechat.class.php';
            //include APP_PATH . './Common/Util/TPWechat.class.php';
            $options = array(
                'agentid'=>'1',
                'token' => 'tokenaccesskey',
                'encodingaeskey' => 'encodingaeskey',
                'appid' => 'wx7bfaceb9ab36ad0d',
                'appsecret' => 'e051cb423d47f5056cac2b4ad1cf0a4f',
                'debug' => true,
                '_logcallback'=>'logg',
            );
            $weObj = new \wechat($options);

            $data = array( 'articles' => array());
            $tplConfig = C('TMPL_PARSE_STRING');
            $is_first = true;
            for ($i = 1; $i <= 8; $i++) {
                $id = I("post.id{$i}", 0, 'intval');
                $type = I("post.type{$i}", '', 'trim');
                $digest = I("post.digest{$i}", '', 'trim');
                if ($id) {
                    $typeModel = M($type);
                    $info = $typeModel->where(array("{$type}_id" => $id))->find();
                    if (!$info) {
                        $this->error('ID号错误');
                    }

                    //图片宽小于300，则保持原来样式，大于300，则宽度强制100%
                    $info['description'] = preg_replace_callback("/<img[^>]+src=\"([^\"]+)\"[^>]*\/>/U", function ($match) {
                        $src = $match[1];
                        if (0 !== strpos($src, 'http')) {
                            $tplConfig = C('TMPL_PARSE_STRING');
                            $src = $tplConfig['__URL_UPLOAD__'] . $src;
                        }
                        preg_match("/\.(jpg|gif|png|jpeg)\.(\d+)x(\d+)\.jpg$/", $src, $imgArr);
                        if (!empty($imgArr[2]) && $imgArr[2] > 300) {
                            $src = str_replace($imgArr[0], '.' . $imgArr[1], $src);
                            $return = "<img style='width: 100%; height: auto;' src=\"{$src}\" />";
                            return $return;
                        } else {
                            $return = $match[0];
                            $return = preg_replace('/src="([^"]+)"/', "src=\"{$src}\"", $return);
                            return $return;
                        }
                    }, $info['description']);

                    //网页类型，description里没有汉字
                    if (!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $info['description'])) {
                        $info['description'] = "<p>{$digest}</p>" . $info['description'];
                    }

                    //多图类型，拼装html
                    if ($info['type'] == 'imgs') {
                        $info['description'] = "<p>{$digest}</p>";
                        $img_arr = explode(',', $info['content']);
                        foreach ($img_arr as $vo) {
                            $info['description'] .= "<p><img src=\"{$tplConfig['__URL_UPLOAD__']}{$vo}\"></p>";
                        }
                    }

                    //第一篇文章取new_img，第二张取share_img
                    $thumb_img = '';
                    if ($is_first) {
                        $thumb_img = $info["{$type}_img"];
                        $is_first = false;
                    } else {
                        $thumb_img = empty($info['share_img']) ? '/uploads/avatar/logo140.png' : $info['share_img'];
                    }
                    $thumb_img = WEB_PATH . '/www' . $thumb_img;
                    $mediaData = array('media' => '@' . $thumb_img);
                    $mediaRs = $weObj->uploadForeverMedia($mediaData, 'image');

                    $title = $type == 'egg' ? $info["egg_name"] : $info["{$type}_title"];
                    $data['articles'][] = array(
                        'title' => $title,
                        'thumb_media_id' => !empty($mediaRs['media_id']) ? $mediaRs['media_id'] : 'oRqMtHrayoGke4bM7PC74ISN3LAyLeFOO7SOu58zEmQ',
                        "author" => '',
                        "digest" => $digest,
                        "show_cover_pic" => 0,
                        "content" => $info['description'],
                        "content_source_url" => '',
                    );
                }
            }
            $result = $weObj->uploadForeverArticles($data);
            if ($result) {
                $this->success('操作成功', array(array('继续发布', U('admin/weixin/uploadarticles'))));
            } else {
                $this->error('操作失败' . $weObj->errCode . $weObj->errMsg);
            }
            exit();
        }

        //微博定时发布
        $this->assign('auto_publish_hours', $this->auto_publish_hours);
        $cModel = M('crontab');
        $pageSize = 10;
        $where = array('identifier' => 'to_weibo');
        $count = $cModel->where($where)->count();
        $pageObj = new \Admin\Util\Page($count, $pageSize);
        $list = $cModel->where($where)->order('auto_publish_time desc')->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();
        $this->assign('list', $list);
        $this->assign('page', $pageObj->show());
        $this->display();
    }

    public function to_weibo() {
        //先检查access_token能不能用
        $sModel = M('site_setting');
        $weibo_access_token = $sModel->where(array('site_key' => 'weibo_access_token'))->getField('site_value');
        $app = C('WEIBO_OAUTH');
        include_once (APP_PATH . "/Common/Util/sina/saetv2.ex.class.php");
        $c = new \SaeTClientV2($app['key'], $app['secret'], $weibo_access_token);
        $uid_get = $c->get_uid();
        if (!is_array($uid_get) || !empty($uid_get['error'])) {
            $this->ajaxReturn('<a href="' . U('/admin/index/signsina') .'" target="_blank">请先绑定微博帐号</a>', 'error', 'TIP_ERROR');
        }

        $auto_publish_time = I('post.auto_publish_time') . ' ' . I('post.auto_publish_hour');
        $type = I('post.type', '', 'trim');
        $myData = array(
            'id' => I('post.id', 0, 'intval'),
            'type' => $type,
            'digest' => I('post.digest', '', 'trim'),
        );
        if ($myData['id'] <= 0) {
            $this->ajaxReturn('', 'error', 'TIP_ERROR');
        }

        $cModel = M('crontab');
        //如果是立即发微博，则立即发
        if ($auto_publish_time == ' ') {
            $app = C('WEIBO_OAUTH');
            include_once (APP_PATH . "/Common/Util/sina/saetv2.ex.class.php");
            $wbObj = new \SaeTClientV2($app['key'], $app['secret'], $weibo_access_token);

            $typeModel = M($type);
            $info = $typeModel->where(array("{$type}_id" => $myData['id']))->find();
            if ($info) {
                $info['share_img'] = empty($info['share_img']) ? '/uploads/avatar/logo140.png' : $info['share_img'];
                $url = "http://{$_SERVER['HTTP_HOST']}/mobile/share/width/650/{$type}_id/" . num_encode($myData['id']);
                $wbObj->upload($myData['digest'] . $url, "http://{$_SERVER['HTTP_HOST']}{$info['share_img']}");

                $data = array(
                    'auto_publish_time' => time(),
                    'data' => json_encode($myData),
                    'status' => 1,
                    'identifier' => 'to_weibo',
                );
                $cModel->add($data);
                $this->ajaxReturn('success', 'success', 'TIP_SUCCESS');
            } else {
                $this->ajaxReturn('id not found', 'error', 'TIP_ERROR');
            }
        }

        $data = array(
            'auto_publish_time' => strtotime($auto_publish_time),
            'data' => json_encode($myData),
            'status' => 0,
            'identifier' => 'to_weibo',
        );
        $cModel->add($data);
        $this->ajaxReturn('success', 'success', 'TIP_SUCCESS');
    }

    public function del_weibo() {
        $id = I('post.id', 0, 'intval');
        $cModel = M('crontab');
        $cModel->where(array('id' => $id))->delete();
        $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
    }

    public function crawler_content() {
        $url = I('get.url', '', 'trim');
        include_once (APP_PATH . "/Common/Util/simple_html_dom.php");
        $str = $this->_curl($url);
        //print_r($str);exit();
        $html = str_get_html($str);
        if (strpos($url, 'http://mp.weixin.qq.com') === 0) {
            $content = $html->find('div[id=js_content]', 0)->innertext;
            $content = preg_replace_callback("/<img[^>]*data-src=\"([^\"]+)\"[^>]*>/U", function ($r) {
                return $this->_saveRemote($r);
            }, $content);
        } elseif (strpos($url, 'http://news.missevan.cn') === 0) {
            $content = $html->find('div[id=articlecontent]', 0)->innertext;
            $content = preg_replace_callback("/<img[^>]*src=\"([^\"]+)\"[^>]*>/U", function ($r) {
                return $this->_saveRemote($r);
            }, $content);
        } elseif (strpos($url, 'http://comic.qq.com') === 0) {
            $content = $html->find('div[id=Cnt-Main-Article-QQ]', 0)->innertext;
            $content = preg_replace_callback("/<img[^>]*src=\"([^\"]+)\"[^>]*>/U", function ($r) {
                return $this->_saveRemote($r);
            }, $content);
        } elseif (strpos($url, 'http://weibo.com/p/') === 0) {
            $content = $html->find('div[class=WBA_content]', 0)->innertext;
            $content = preg_replace_callback("/<img[^>]*src=\"([^\"]+)\"[^>]*>/U", function ($r) {
                return $this->_saveRemote($r);
            }, $content);
        } elseif (strpos($url, 'http://www.udongman.cn') === 0) {
            $content = $html->find('div[class=sucai_intro_detail]', 0)->innertext;
            $content = preg_replace_callback("/<img[^>]*src=\"([^\"]+)\"[^>]*>/U", function ($r) {
                return $this->_saveRemote($r);
            }, $content);
        } else {
            $content = '暂时不支持抓取此网址';
        }

        exit($content);
    }

    private function _curl($url, & $ch_info = array()) {
        $timeout = 30;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }

    private function _saveRemote($match) {
        $source = $match[1];
        $up = new \Admin\Util\Uploader();
        $up->saveRemote($source);
        $fileInfo = $up->getFileInfo();
        $up->imkThumb($fileInfo['url'], 450, 0, 'ratable');
        $up->imkThumb($fileInfo['url'], 650, 0, 'ratable');

        //大于450的图直接用450的缩略图
        preg_match("/\.(\d+)x(\d+)\./", $fileInfo['url'], $match);
        if (!empty($match[1]) && $match[1] >= 450) {
            $fileInfo['url'] = getRatableImg($fileInfo['url'], 450);
        }
        $return = "<img src=\"{$fileInfo['url']}\" />";
        return $return;
    }
}